from django.contrib import admin
from .models import FuturesHistory, FuturesCurrent, ConfigDictionary
from .models import AkCodeConfig  # 同时导入其他模型
from django.utils.html import format_html  # 新增导入
from django.utils.translation import gettext_lazy as _
from akshare_analysis.qihuo_list_his import fetch_futures_his_data
import logging

# 获取自定义日志器（与 settings.py 中的 'app' 对应）
logger = logging.getLogger('app')

class LaunchYearFilter(admin.SimpleListFilter):
    title = _('上市年份')
    parameter_name = 'launch_year'

    def lookups(self, request, model_admin):
        # 返回年份选项列表
        years = FuturesCurrent.objects.exclude(launch_date__isnull=True).values_list('launch_date', flat=True)
        year_set = set()
        for date_int in years:
            if date_int:
                year = int(str(date_int)[:4])  # 提取年份
                year_set.add((year, _(str(year))))
        return sorted(list(year_set), reverse=True)

    def queryset(self, request, queryset):
        if self.value():
            # 筛选小于或等于选定年份的所有数据
            year_end = int(self.value()) * 10000 + 1231  # 选定年份的结束日期
            return queryset.filter(launch_date__lte=year_end)
        return queryset


@admin.register(FuturesHistory)
class FuturesHistoryAdmin(admin.ModelAdmin):
    list_display = (
        'exchange', 'breed', 'code', 'code_complete', 'current', 'current_to_lowest', 'trans_date', 'minimum',
        'highest',
        'lowest_to_highest', 'min_date', 'create_time','update_time')
    # search_fields = ('exchange', 'breed', 'code', 'code_complete')
    list_filter = ('exchange', 'breed', 'ak_code', 'code_complete', 'trans_date')
    readonly_fields = ('create_time', 'update_time')  # 只读字段
    list_per_page = 20  # 每页显示 20 条记录，可根据需求调整
    ordering = ('-trans_date',)
    fieldsets = (
        ('基本信息', {
            'fields': (
                'exchange', 'breed', 'code', 'code_complete', 'ak_code', 'current', 'current_to_lowest',
                'minimum', 'highest', 'lowest_to_highest', 'min_date')
        }),
        ('操作记录', {
            'fields': ('create_by', 'create_time', 'update_by', 'update_time'),
            'classes': ('collapse',)  # 默认折叠
        }),
    )


@admin.register(FuturesCurrent)
class FuturesCurrentAdmin(admin.ModelAdmin):
    list_display = (
        'ak_code', 'exchange', 'breed', 'code', 'code_complete', 'current', 'current_to_lowest', 'minimum', 'highest',
        'min_date', 'hold', 'trans_date', 'launch_date',
        'create_time', 'update_time', 'time_period_buttons'  # 新增按钮列
    )
    list_filter = ('exchange', 'breed', 'ak_code', 'code_complete', LaunchYearFilter)
    readonly_fields = ('create_time', 'update_time')
    list_per_page = 20
    ordering = ('current_to_lowest',)
    fieldsets = (
        ('基本信息', {
            'fields': (
                'exchange', 'breed', 'code', 'code_complete', 'ak_code', 'current_to_lowest', 'current', 'minimum', 'highest')
        }),
        ('操作记录', {
            'fields': ('create_by', 'create_time', 'update_by', 'update_time'),
            'classes': ('collapse',)
        }),
    )
    # 添加媒体资源：引入Chart.js和自定义JS处理文件
    class Media:
        js = (
            # 'https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js',  # Chart.js用于绘制折线图
            'js/chart.umd.min.js',
            'js/period_handler.js',  # 自定义处理按钮点击和图表渲染的JS文件
        )
    # 新增：时间周期按钮列
    def time_period_buttons(self, obj):
        # 使用format_html确保HTML标签被正确渲染，修改为传递ak_code
        return format_html(
            '<a class="button" href="javascript:void(0);" onclick="handlePeriod(\'{ak_code}\', \'daily\')">日线</a>&nbsp;'
                        '<a class="button" href="javascript:void(0);" onclick="handlePeriod(\'{ak_code}\', \'weekly\')">周线</a>&nbsp;'
                        '<a class="button" href="javascript:void(0);" onclick="handlePeriod(\'{ak_code}\', \'monthly\')">月线</a>',
            ak_code=obj.ak_code  # 传递ak_code用于关联FuturesHistory数据
        )

    time_period_buttons.short_description = '时间周期'  # 列标题
    time_period_buttons.allow_tags = True  # 允许HTML标签渲染

@admin.register(AkCodeConfig)
class AkCodeConfigAdmin(admin.ModelAdmin):
    # 列表页显示的字段
    list_display = ('ak_code', 'exchange', 'breed', 'code_complete', 'is_pull', 'create_time', 'update_time')
    # 搜索字段
    # search_fields = ('ak_code', 'exchange', 'breed', 'code', 'code_complete')
    # 筛选器
    list_filter = ('exchange', 'ak_code', 'breed', 'code', 'code_complete', 'is_pull')
    # 添加actions
    actions = ['pull_selected_data']
    # 编辑页的字段布局（分栏显示，更清晰）
    fieldsets = (
        ('基本信息', {
            'fields': ('ak_code', 'exchange', 'breed', 'code', 'code_complete')
        }),
        ('状态配置', {
            'fields': ('is_pull',)
        }),
        ('操作记录', {
            'fields': ('create_by', 'create_time', 'update_by', 'update_time'),
            'classes': ('collapse',)  # 默认折叠
        }),
    )
    # 只读字段（根据需要调整，这里放开update_time允许手动修改）
    readonly_fields = ('create_time',)
    list_per_page = 20  # 每页显示 20 条记录，可根据需求调整
    ordering = ('ak_code',)

    # 定义action方法
    def pull_selected_data(self, request, queryset):
        # 遍历 queryset 中的每个对象
        for obj in queryset:
            try:
                # 调用 fetch_futures_his_data 处理单个对象
                fetch_futures_his_data(obj)
                logger.info(f"成功获取 {obj.ak_code} 的历史数据")
            except Exception as e:
                logger.error(f"获取 {obj.ak_code} 的历史数据失败: {str(e)}")
    # 设置中文显示名称
    pull_selected_data.short_description = "拉取"

@admin.register(ConfigDictionary)
class ConfigDictionaryAdmin(admin.ModelAdmin):
    list_display = ('dic_key', 'dic_value', 'dic_remark', 'create_time', 'update_time')
    # search_fields = ('dic_key', 'dic_value', 'dic_remark')
    list_filter = ('dic_key', 'dic_remark')
    fieldsets = (
        ('配置信息', {
            'fields': ('dic_key', 'dic_value', 'dic_remark')
        }),
        ('操作记录', {
            'fields': ('create_time', 'update_time'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ('create_time', 'update_time')
    list_per_page = 20
    ordering = ('dic_key',)